package com.bedrock.common.utils;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.PostConstruct;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.bedrock.common.constant.RecruitConstants;
import com.bedrock.project.inside.vo.request.MailVo;
import com.bedrock.project.inside.vo.response.ProjectInfoResVo;
import com.bedrock.project.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author yuanql
 * @date 2020/4/15
 */
@Component
public class EmailUtils {

        @Autowired
        private ISysConfigService configService;
        private static EmailUtils emailUtils;
        @PostConstruct
        public void init(){
            emailUtils = this;
            emailUtils.configService = this.configService;
        }


        public static void sendMail(MailVo mailVo) throws Exception {
            String myEmailInfo = emailUtils.configService.selectConfigByKey(RecruitConstants.EMAIL_CONFIG);
            //系统配置  "email.config" 中配置发件人信息 包含邮箱账户/授权码/stmp服务器地址 用 / 分割
            // 对于开启了独立密码的邮箱, 这里的邮箱密码必需使用这个独立密码（授权码）。
            String myEmailAccount=myEmailInfo.split("/")[0];
            String myEmailPassword = myEmailInfo.split("/")[1];
            // 发件人邮箱的 SMTP 服务器地址
            String myEmailSMTPHost = myEmailInfo.split("/")[2];
            // 1. 创建参数配置, 用于连接邮件服务器的参数配置
            Properties props = new Properties();
            // 发件人的邮箱的 SMTP 服务器地址
            props.setProperty("mail.smtp.host", myEmailSMTPHost);
            // 使用的协议（JavaMail规范要求）
            props.setProperty("mail.transport.protocol", "smtp");
            // 需要请求认证
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");
            // 2. 根据配置创建会话对象, 用于和邮件服务器交互
            Session session = Session.getInstance(props);
            // 设置为debug模式, 可以查看详细的发送 log
            session.setDebug(false);
            // 3. 创建一封邮件
            MimeMessage message = createMimeMessage(session, myEmailAccount, mailVo);
            // 4. 根据 Session 获取邮件传输对象
            Transport transport = session.getTransport();
            //连接邮箱
            transport.connect(myEmailAccount, myEmailPassword);
            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());
            // 7. 关闭连接
            transport.close();
        }

        /**
         * 创建一封只包含文本的简单邮件
         *
         * @param session     和服务器交互的会话
         * @param sendMail    发件人邮箱
         * @param mailVo      邮件信息
         * @return
         * @throws Exception
         */
        public static MimeMessage createMimeMessage(Session session, String sendMail, MailVo mailVo) throws Exception {
            // 1. 创建一封邮件
            MimeMessage message = new MimeMessage(session);
            // 2. From: 发件人
            message.setFrom(new InternetAddress(sendMail));

            message.setRecipients(MimeMessage.RecipientType.TO, InternetAddress.parse(mailVo.getToMails()));
            if(StringUtils.isNotEmpty(mailVo.getCcMails())) {
                message.setRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(mailVo.getCcMails()));
            }
            if(StringUtils.isNotEmpty(mailVo.getBccMails())) {
                message.setRecipients(MimeMessage.RecipientType.BCC, InternetAddress.parse(mailVo.getBccMails()));
            }
            // 4. Subject: 邮件主题
            message.setSubject(mailVo.getSubject(), "UTF-8");
            // 5. Content: 邮件正文（可以使用html标签）
            message.setContent(mailVo.getContent(), "text/html;charset=UTF-8");
            // 6. 设置发件时间
            message.setSentDate(new Date());
            // 7. 保存设置
            message.saveChanges();
            return message;
        }


    public static String getOneWeekDay(){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dayFormat = new SimpleDateFormat("M.d");
        String endDay = dayFormat.format(calendar.getTime());
        calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)-4);
        String beginDay = dayFormat.format(calendar.getTime());
        return beginDay +"-"+endDay;
    }

    public static String getCurrentDay(){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dayFormat = new SimpleDateFormat("M.d");
        String currentDay = dayFormat.format(calendar.getTime());
        return currentDay;
    }

    public static String getCurrentWeek(){
        SimpleDateFormat monthFormat = new SimpleDateFormat("y年M月第W周");
        String week = monthFormat.format(DateUtils.getNowDate());
        return week;
    }


}
